package {
	import net.flashpunk.Entity;
	import net.flashpunk.utils.Input;
	import net.flashpunk.utils.Key;
	import net.flashpunk.World;
	import net.flashpunk.FP;
	
	/**
	 * ...
	 * @author Guido
	 */
	public class SudokuDemonstration extends World {
		private static var instance:SudokuDemonstration;
		private var currentRow:int;
		private var currentColumn:int;
		private var isOver:Boolean;
		private var board:Board;
		private var selectedBlock:Block;
		
		public function SudokuDemonstration(){
			instance = this;
			isOver = false;
			currentRow = 1;
			currentColumn = 1;
			board = new Board();
			selectedBlock = null;
			FP.screen.color = 0x00FFF0;
		}
		
		override public function update():void {
			super.update();
			if (!isOver){
				if (Input.pressed(Key.ENTER)){
					defineNextBlock();
				}
				//TODO temporario lo que sigue
				if (Input.mousePressed){
					var b:Block = collidePoint("block", mouseX, mouseY) as Block;
					if (b){
						selectedBlock = b;
					}
				}
				if (selectedBlock){
					selectedBlock.receiveInput();
				}
			}
		}
		
		private function defineNextBlock():void {
			var tempCol:int;
			var tempRow:int;
			
			var block:Block = board.getBlock(currentRow, currentColumn);
			var number:int = block.assignRandomPosibility();
			for (tempCol = 1; tempCol < 10; tempCol++){
				board.getBlock(currentRow, tempCol).removePosibility(number);
			}
			for (tempRow = 1; tempRow < 10; tempRow++){
				board.getBlock(tempRow, currentColumn).removePosibility(number);
			}
			var minRow:int = ((currentRow - 1) / 3) * 3 + 1;
			var maxRow:int = ((currentRow - 1) / 3) * 3 + 3;
			var minCol:int = ((currentColumn - 1) / 3) * 3 + 1;
			var maxCol:int = ((currentColumn - 1) / 3) * 3 + 3;
			for (tempRow = minRow; tempRow <= maxRow; tempRow++){
				for (tempCol = minCol; tempCol <= maxCol; tempCol++){
					board.getBlock(tempRow, tempCol).removePosibility(number);
				}
			}
			
			currentColumn++;
			if (currentColumn == 10){
				currentColumn = 1;
				currentRow++;
				if (currentRow == 10){
					isOver = true;
				}
			}
		}
		
		public static function get world():SudokuDemonstration {
			return instance;
		}
		
		private function random(minNum:int, maxNum:int):int {
			return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
		}
	}

}